﻿using System.Data.Entity;
using System.Data;
using Data.Api.Db;
using Data.ModelDatabase;
using System;
using System.Collections.Generic;

namespace Data.Db
{
    public class ShopContext : DbContext, IDbShopConcreteContext
    {
        public IDbSet<Category> Categories { get; set; }
        public IDbSet<Product> Products { get; set; }
        public IDbSet<User> Users { get; set; }
        public IDbSet<Role> Roles { get; set; }
        public IDbSet<OrderPosition> OrderPosition { get; set; }
        public IDbSet<OrderEntry> OrderEntry { get; set; }
        public IDbSet<Basket> Basket { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Category>().HasMany(p => p.Products).WithMany(c => c.Categories);
            modelBuilder.Entity<Product>().HasMany(c => c.Categories).WithMany(c => c.Products);

            modelBuilder.Entity<User>().HasMany(p => p.Roles).WithMany(c => c.Users);

            modelBuilder.Entity<User>().HasMany(x => x.Basket).WithRequired(i => i.User).WillCascadeOnDelete(false);
            modelBuilder.Entity<User>().HasMany(x => x.LogEntry).WithRequired(i => i.User).WillCascadeOnDelete(false);

            base.OnModelCreating(modelBuilder);
        }

        public bool Delete()
        {      
            return this.Database.Delete();
        }

        public void Commit()
        {
            this.SaveChanges();
        }


        public DbContext Context
        {
            get
            {
                return this;
            }
        }
    }
}
